import Vue from "vue";
import Store from "@/store/index";
import router from "../router/index";
// 个人信息
import { getUserProfile } from "@/api/system/user.js";
import { getMessageList, getName, getImList } from "@/BMViews/api/upload/index.js";
let _this = this;
/**
 * Websocket
 *
 * @param {Object} rules 验证字段的规则
 * @param {Object} messages 验证字段的提示信息
 *
 */
class Websocket {
  constructor(wsUrl = "", wsId = 1) {
    Object.assign(this, {
      data: {
        wsUrl:wsUrl,
        wsId:wsId,
        //是否连接
        //是否连接
        linkState: false,
        linkIng: false,		//连接中，连接锁
        //websocket对象
        wss: "",
        // 用户id
        userId: "",
        //全局消息数
        unreadMsg: 0,
        //分页
        pageNum: 1,
        pageSize: 10,
        //所有订单
        totalList: [],
        //心跳包定时器
        timer: "",
        //断连定时器
        timerCl: "",
        //最大重连数
        reconnectNum:0,
      },
    });
    this.__init();
  }

  /**
   * __init
   */
  __init() {
    this.__initMethods();
    this.__initDefaults();
    this.__initData();
  }

  /**
   * 初始化数据
   */
  __initData() {}

  /**
   * 初始化默认提示信息
   */
  __initDefaults() {
    this.defaults = {
      messages: {
        required: "这是必填字段。",
      },
    };
  }

  /**
   * 初始化
   */
  __initMethods() {
    // console.log("初始化ws");
  }

  //初始化WebSocket
  initialize(url) {
    return new Promise(async (resolve, reject) => {
      let token = localStorage.getItem("token");
      let userId = localStorage.getItem("userId");
      if (!token) {
        return false;
      }
      //如果用户登录但是没有userId就请求接口
      if (token && !userId) {
        let { code, data } = await getUserProfile();
        if (code == 200) {
          userId = data.userId;
        }
      }

      url = `${this.data.wsUrl}/${token}?id=${userId}`;
      console.log(url);
      //实例化WebSocket 开始连接
      this.wss = new WebSocket(url);
      //监听连接事件
      this.wss.onopen = (res) => {
        console.log("监听连接事件", res);
        console.log(`WebSocket ${this.data.wsId}全局连接成功`, this.wss);
        // if(this.data.wsId == 1){
        //   this.getOrderNoList();
        // }else if(this.data.wsId == 2){
        //   this.getImList()
        // }
        //发送心跳包
        this.heartbeatPacket();
        //开启消息监听
        this.onMessage();
        //开启关闭监听
        this.onClose();
        this.wss.onerror = function (e) {
          // console.log("连接失败");
        };
        resolve(true);
      };
    });
  }

  //连接
  wsss() {
    return this.wss;
  }


  //发送心跳包
  heartbeatPacket() {
    //50秒发送一次心跳
    this.timer = setInterval(() => {
      // console.log("发送心跳包");
      var data = { type: "0" };
      this.onSend(JSON.stringify(data));
    }, 50000);
  }

  //连接 接受消息
  onMessage() {
    // let that = this;
    this.wss.onmessage = async (e) => {
      let data = JSON.parse(e.data);
      console.log(
        data,
        Store.getters.userId,
        "--------------------------------------全局消息"
      );
      if (data.type == "0") return false;
      if (data.type == "f1") return false;	//收到邀请通知
      if (data.type == 5) return false;	//收到邀请通知
      // let aaa = await this.getOrderNoList();
      // if (aaa) {
      //收到消息
      if (data.Long2Str) {
        // (id，sessionId，createBy)
        let Long2Str = data.Long2Str.split('，');
        if(Long2Str.length>2){
          data.data.id = Long2Str[0];		//消息id
          data.data.sessionId = Long2Str[1]; 	// 发送人的id
          data.data.createBy = Long2Str[2]; 	// 发送人的id
        }
      }
      if(data.data.reads && data.data.reads == "[]"){
      	data.data.reads = [];
      }
      //收到消息后如果当前页面是聊天室，更新聊天室内容
      console.log(router.currentRoute.path);
      if (router.currentRoute.path == "/Bm-personalCenter/messageCenter" || router.currentRoute.path == "/Bm-messageCenter/messageCenter") {
        console.log('发送给聊天页面');
        $bus.$emit("uploadMessage", data);
      }

      if(data.type == 2) return false;
      if(data.type == 3) return false;
      if (data.data.createBy && data.data.createBy != Store.getters.userId) {
        //不是自己发出去的消息
        let msgText = data.data.msg
        if(data.data.type == 2){
          if(this.matchType(data.data.msg) == "image"){
            msgText = '【图片】'
          }else{
            msgText = '【文件】'
          }
        }
        if(this.data.wsId == 1){
          //圈聊
          //如果不是是自己则数量加1，否则不操作
          Store.dispatch('chat/addUnread',{
            'orderUnread': 1
          })
          // this.data.unreadMsg++;
          // $bus.$emit("unreadMsg", this.data.unreadMsg);
          //更新列表未读数量
          // ------------pc端获取消息闪烁------------
          if($ipcRenderer){
            //订单
            let orderList = Store.state.chat.orderList //私聊用户列表
            let orderInfo = orderList.find(item=> item.id == data.no)
            $ipcRenderer.send('showNotification', {"title": orderInfo ? orderInfo.name:'聊天消息', "msg": msgText})
          }
          // ------------pc端获取消息闪烁------------end
        }else{
          //私聊

          //未读加1
          this.addImSum(data);
          // this.data.unreadMsg++;
          // $bus.$emit("unreadImMsg", this.data.unreadMsg);
          //更新列表未读数量
          // ------------pc端获取消息闪烁------------
          if($ipcRenderer){
            let userList = Store.state.chat.userLists; //私聊用户列表
            let user = userList.find(item=> item.userId == data.data.createBy)
            if(user){
              $ipcRenderer.send('showNotification', {"title": user.nickName || user.name, "msg": msgText})
            }else{
              let {code,data} = await getName({userIds: data.data.createBy})
              // $ipcRenderer.send('showNotification', {"title": '朋友消息', "msg": msgText})
              $ipcRenderer.send('showNotification', {"title": data[0].nickName, "msg": msgText})
            }
          }
          // ------------pc端获取消息闪烁------------end
        }
      }
    }
  }

  // 判断图片文件
  matchType(fileUrl) {
  	// 后缀获取
  	var suffix = "";
  	// 获取类型结果
  	var result = "";
  	try {
  		var flieArr = fileUrl.split(".");
  		suffix = flieArr[flieArr.length - 1];
  	} catch (err) {
  		suffix = "";
  	}
  	// fileUrl无后缀返回 false
  	if (!suffix) {
  		result = false;
  		return result;
  	}
  	// 图片格式
  	var imglist = ["png", "jpg", "jpeg", "bmp", "gif", "JPG", "PNG", "GIF"];
  	// 进行图片匹配
  	result = imglist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "image";
  		return result;
  	}
  	// 匹配txt
  	var txtlist = ["txt"];
  	result = txtlist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "txt";
  		return result;
  	}
  	// 匹配 excel
  	var excelist = ["xls", "xlsx", "numbers"];
  	result = excelist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "excel";
  		return result;
  	}
  	// 匹配 word
  	var wordlist = ["doc", "docx"];
  	result = wordlist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "word";
  		return result;
  	}
  	// 匹配 pdf
  	var pdflist = ["pdf", "PDF"];
  	result = pdflist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "pdf";
  		return result;
  	}
  	// 匹配zip
  	var ziplist = ["zip", "rar", "exe", "tgz"];
  	result = ziplist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "zip";
  		return result;
  	}
  	// 匹配 ppt
  	var pptlist = ["ppt", "pptx", "key"];
  	result = pptlist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "ppt";
  		return result;
  	}
  	// 匹配 视频
  	var videolist = ["mp4", "m2v", "mkv"];
  	result = videolist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "video";
  		return result;
  	}
  	// 匹配 音频
  	var radiolist = ["mp3", "wav", "wmv"];
  	result = radiolist.some(function(item) {
  		return item == suffix;
  	});
  	if (result) {
  		result = "radio";
  		return result;
  	}
  	// 其他 文件类型
  	result = "other";
  	return result;
  }

  //修改变量
  addImSum(data) {
    //如果不是自己则数量加1，否则不操作
    let imList = Store.state.chat.imList
    let info = imList.find(item=> item.id == data.no)
    if(info){
      // if(info.type === '0' || info.type === '1')
      Store.dispatch('chat/addUnread',{
        'imUnread': 1
      })
      return false;
    }
    let taskList = Store.state.chat.taskList
    info = taskList.find(item=> item.id == data.no)
    if(info){
      Store.dispatch('chat/addUnread',{
        'taskUnread': 1
      })
    }
  }

  //减少数量
  reduceNum(val) {
    // console.log(val, "减少数量");
    this.data.unreadMsg = this.data.unreadMsg - val;
    if (this.data.unreadMsg < 0) {
      this.data.unreadMsg = 0;
    }
    // console.log(this.data.unreadMsg, "减少后数量");
    if(this.data.wsId == 2){
      $bus.$emit("unreadImMsg", this.data.unreadMsg);

    }else{
      $bus.$emit("unreadMsg", this.data.unreadMsg);
    }
  }


  //发送信息
  onSend(data) {
    console.log('发送数据',data);
    this.wss.send(data);
  }

  //关闭连接
  onClose() {
    this.wss.onclose = (e) => {
      // console.log("监听关闭事件", e); //监听关闭事件
      // // console.log(
      //   "websocket 断开: " + e.code + " " + e.reason + " " + e.wasClean
      // );
      // 停掉心跳包发送
      window.clearInterval(this.timer);
      //判断断链原因
      if (navigator.onLine) {
        //有网络
        this.initialize();
        //来网了（有网的情况下有三次重连的机会） //30秒执行一次
        let i = 0;
        this.timerCl = setInterval(() => {
          //如果当前连接状态为三，彻底断开重新连接
          if (this.wss.readyState > 2) {
            //已断开连接
            this.initialize();
            // console.log("websocket连接");
            i++;
            if (i == 3) {
              window.clearInterval(this.timerCl);
            }
          } else {
            window.clearInterval(this.timerCl);
          }
        }, 30000);
      }
    };
  }
}

export default Websocket;
